package com.boarsoft.hibernate.biz;

import java.beans.PropertyDescriptor;
import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;

import com.boarsoft.common.Util;
import com.boarsoft.hibernate.dao.SimpleDao;

@SuppressWarnings("rawtypes")
public class SimpleBizImpl implements SimpleBiz {
	protected Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
//	@Qualifier("simpleDao")
	protected SimpleDao dao;

	/**
	 * 用一个 Hibernate 代理的实体对象填充对应的 POJO 对象，但排除某些属性
	 * 
	 * @param source
	 * @param targetClass
	 * @param excludes
	 * @return
	 */
	@Override
	public <T> T transfer(Object source, Class<T> targetClass, String[] excludes) {
		T result = null;
		try {
			result = targetClass.newInstance();
			BeanWrapper bws = new BeanWrapperImpl(source);
			BeanWrapper bwt = new BeanWrapperImpl(result);
			//
			PropertyDescriptor[] pds = bws.getPropertyDescriptors();
			for (PropertyDescriptor pd : pds) {
				Class pc = pd.getPropertyType();
				if (source.getClass().getPackage().equals(pc.getPackage()) || Collection.class.isAssignableFrom(pc))
					continue;
				String s = pd.getName();
				if (Util.inArray(s, excludes) >= 0)
					continue;
				if (bws.isReadableProperty(s) && bwt.isWritableProperty(s)) {
					bwt.setPropertyValue(s, bws.getPropertyValue(s));
				}
			}
		} catch (Exception e) {
			log.error("Error on transfer", e);
		}
		return result;
	}

	/**
	 * 用一个 Hibernate 代理的实体对象填充对应的 POJO 对象
	 * 
	 * @param source
	 * @param targetClass
	 * @return
	 */
	public <T> T transfer(Object source, Class<T> targetClass) {
		return transfer(source, targetClass, null);
	}

	public SimpleDao getDao() {
		return dao;
	}

	public void setDao(SimpleDao dao) {
		this.dao = dao;
	}
}